package com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.dao.TaxBillGoodsDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.entity.TaxBillGoods;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Lianhong
 * @since 2022/4/19
 */
@Service
public class TaxBillGoodsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaxBillService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private TaxBillGoodsDao taxBillGoodsDao;

    public void saveTaxBillGoods(String taxBillGoods) {
        if (StringUtils.isEmpty(taxBillGoods)) return;
        String taxBillsGoodsText = SecurityUtil.decrypt3DES(token, taxBillGoods);
        try {
            JSONObject taxBillObj = JSON.parseObject(taxBillsGoodsText);
            if (taxBillObj == null) return;
            String socialCreditCode = taxBillObj.getString("socialCreditCode");
            String taxHeadSeqNo = taxBillObj.getString("taxHeadSeqNo");
            JSONObject taxBillGoodsObj = taxBillObj.getJSONObject("taxBillGoods");
            if (taxBillGoodsObj == null) return;

            //电子税单货物信息
            TaxBillGoods goods = new TaxBillGoods(taxHeadSeqNo, taxBillGoodsObj, socialCreditCode);

            taxBillGoodsDao.deleteBy(taxHeadSeqNo);

            taxBillGoodsDao.save(goods);
        } catch (Exception e) {
            LOGGER.error("保存税费单错误", e);
        }
    }

    public boolean taxBillGoodsExists(String taxHeadSeqNo) {
        return taxBillGoodsDao.exists(taxHeadSeqNo);
    }

    public String getTaxBillGoods(String taxHeadSeqNo) {
        TaxBillGoods goods = taxBillGoodsDao.findBy(taxHeadSeqNo);
        if (goods == null) return StringUtils.EMPTY;
        return SecurityUtil.encrypt3DES(token, goods.getTaxBillGoods());
    }
}
